package com.naizhuai.ui.task;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.TaskActionApiStore;
import com.naizhuai.network.apistore.UserManageDataApiStore;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.entity.Bus.Bus;
import com.naizhuai.ui.entity.ImgBean;
import com.naizhuai.ui.entity.StepJoin;
import com.naizhuai.ui.entity.Task.TaskFlowItem;
import com.naizhuai.ui.task.adapter.TaskExplainAdapter;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AlbumUtils;
import com.naizhuai.util.BitmapUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.RxBus;
import com.naizhuai.util.ViewUtils;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public class StepSettingActivity extends BaseActivity {
    private static String TASKFLOWID = "TASKFLOWID";
    public static void start(Context context,  String taskFlowid) {
        Intent intent = new Intent(context, StepSettingActivity.class);
        intent.putExtra(TASKFLOWID, taskFlowid);
        context.startActivity(intent);
    }
    @BindView(R.id.toolbar)
    Toolbar settingToolbar;
    @BindView(R.id.imgTextinfo)
    ImageView imgTextinfo;
    @BindView(R.id.textlist)
    RecyclerView textlist;
    @BindView(R.id.editImg)
    ImageView editImg;
    @BindView(R.id.editlist)
    RecyclerView editlist;
    @BindView(R.id.btn_release)
    Button tvRelease;
    @BindView(R.id.stepname)
    TextView stepname;
    @BindView(R.id.step_cycle)
    TextView stepCycle;
    private TaskActionApiStore mTaskActionApiStore;
    private UserManageDataApiStore mUserManageDataApiStore;
    private TaskExplainAdapter mTaskExplainAdapter;
    private TaskExplainAdapter mTaskEditTextAdapter;
    private String imgpath = "";
    private  @NonNull TaskFlowItem.FlowItem  flowItem;
    private String taskFlowid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        InitView();
        InitData();
        InitTextAdapter();
    }

    private void InitView() {
        taskFlowid = getStrExtra(TASKFLOWID);

        settingToolbar.setNavigationOnClickListener(v -> finish());
    }

    private void InitTextAdapter() {
        mTaskExplainAdapter = new TaskExplainAdapter();
        mTaskExplainAdapter.setEditEnable(false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        textlist.setLayoutManager(layoutManager);
        textlist.setAdapter(mTaskExplainAdapter);

        ArrayList<String> list1 = new ArrayList();
        list1.add("");
        list1.add("");
        list1.add("");
        list1.add("");
//        List<String> strings = Arrays.asList("", "","","");
        mTaskEditTextAdapter = new TaskExplainAdapter(list1);
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        editlist.setLayoutManager(layoutManager1);
//        editlist.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.padding_default_min)));
        editlist.setAdapter(mTaskEditTextAdapter);
    }

    private void InitData() {
        if (mTaskActionApiStore == null) {
            mTaskActionApiStore = TaskActionApiIml.getInstance();
        }

        if (mUserManageDataApiStore == null) {
            mUserManageDataApiStore = UserManageDataApiStoreIml.getInstance();
        }
        showWaitDiaLog();
        mTaskActionApiStore.task_flow_joined(taskFlowid)
                .subscribe(new NetWorkObserver<StepJoin>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(StepJoin join) {
                        flowItem=new TaskFlowItem.FlowItem(join.stepName,taskFlowid,join.cycleType);
                        hideWaitDialog();
                        stepname.setText(String.format(getString(R.string.stepname),join.stepName));
                        stepCycle.setText(join.weekendCount);
                        ViewUtils.showImg(join.imageUrl,imgTextinfo);
                        mTaskExplainAdapter.setStringList(join.detail);
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_step_setting;
    }


    @OnClick(R.id.editImg)
    public void onEditImg() {
        AlbumUtils.singleChoice(this)
                  .subscribe(albumFile -> {
                      imgpath = albumFile.getPath();
                      File file = new File(albumFile.getPath());
                      Glide.with(StepSettingActivity.this)
                              .load(file).into(editImg);
                  });
    }

    @OnClick(R.id.btn_release)
    public void onBtnRelease() {
        //先上传图片的 然后在上传用户的信息 图片
        if (TextUtils.isEmpty(imgpath)) {
            shortToast(getString(R.string.please_settting_image));
            return;
        }
        String detital = mTaskEditTextAdapter.getTaskString();
        if (TextUtils.isEmpty(detital)) {
            shortToast(getString(R.string.task_please_input_flowdetial));
            return;
        }
        showWaitDialog(getString(R.string.data_uploading));
        //先进行图片压缩的操作 然后返回压缩的路径 用压缩的路径 上传图片
        Observable.just(imgpath)
                  .subscribeOn(Schedulers.io())
                  .map(imagepath -> {
                    //通过这个Path 压缩图片 并且返回压缩图片的路径 然后下发
                    Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
                    File file = BitmapUtils.changeBitmap2File(bitmap, StepSettingActivity.this, "temp.jpeg");
                    return file.getPath();
                })
                .flatMap(imagepath -> mUserManageDataApiStore.uploadImg(imagepath))
                .flatMap(bean ->
                        mTaskActionApiStore.leader_set_task_flow(flowItem.flowId, bean.getImgUrl(), detital, flowItem.flowName, flowItem.flowCircleType))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                        hideWaitDialog();
                    }
                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if (!"0".equals(result)) {
                            shortToast(getString(R.string.release_success));
                            finish();
                            RxBus.getDefault().postSticky(new Bus.ReFreshTask());
                        }
                    }
                 });
    }
}
